package com.glacier.proxy.factory;

import com.glacier.proxy.cglib.DebugMethodInterceptor;
import com.glacier.proxy.cglib.EnhancedMethodInterceptor;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.cglib.proxy.Enhancer;

/**
 * date 2024-01-17 19:47
 *
 * @author glacier
 * @version 1.0
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ProxyFactory {

    /**
     * 通过该方法可以生成任意目标类所对应的代理类
     *
     * @param clazz 被代理对象类
     * @return 代理对象
     */
    public static Object getProxy(Class<?> clazz) {
        return Enhancer.create(clazz, clazz.getInterfaces(), new DebugMethodInterceptor());
    }

    /**
     * 通过该方法可以生成任意目标类所对应的代理类
     *
     * @param target 被代理对象
     * @return 代理对象
     */
    public static Object createProxy(Object target) {
        Enhancer e = new Enhancer();
        e.setSuperclass(target.getClass());
        e.setCallback(new EnhancedMethodInterceptor(target));
        return e.create();
    }

    /**
     * 通过该方法可以生成任意目标类所对应的代理类
     *
     * @param target 被代理对象
     * @return 代理对象
     */
    public static Object createProxy(Object target, Class<?>[] argumentTypes, Object[] arguments) {
        Enhancer e = new Enhancer();
        e.setSuperclass(target.getClass());
        e.setCallback(new EnhancedMethodInterceptor(target));
        return e.create(argumentTypes, arguments);
    }
}
